import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/site/site_list/site_list_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/site/site_services.dart';

class MineSiteManagerController extends GetxController {
  /// 站点列表
  List<SiteModel> siteModelList = [];

  /// 站点列表服务
  SiteServices siteServices = Get.put(SiteServices());
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  int currentPage = 1;
  int pageSize = 10;
  // final TextEditingController searchController = TextEditingController();
  String searchName = '';
  bool isLoading = false;//是否请求过数据,如果请求且为空则显示空
  @override
  void onInit() {
    super.onInit();
    getSiteList();
  }

  getSiteList() async {
    var params = {
      'siteName': searchName,
      'status': 2,
      'current': currentPage,
      'pageSize': 20
    };
    showLoading(toast: ResKey.loading.tr);
    var list = await siteServices.getSitesList(params, onError: (error) {
      dismissLoading();
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      handleException(error);
      return false;
    });
    dismissLoading();
    refreshController.loadComplete();
    refreshController.refreshCompleted();
    isLoading = true;
    var temp =
        List.of(list['list']).map((item) => SiteModel.fromJson(item)).toList();
    if (currentPage == 1) {
      siteModelList?.clear();
    }
    siteModelList!.addAll(temp);
    if(list != null && list['total'] != null && (list['total'] <= siteModelList!.length)){
      refreshController.loadNoData();
    }
    update();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  addNewSite() {


      Get.toNamed(RouterPath.taskCreateSite,arguments: {
        'isCreateSite':true
      })?.then((value) {
        if (value == true) {
              onRefresh();
        }});

  }

  ///刷新
  void onRefresh() async {
    Log.d('onRefresh==');

    currentPage = 1;
    getSiteList();
  }

  ///加载更多
  void onLoading() async {
    currentPage++;
    getSiteList();
  }
}
